package cn.iocoder.yudao.module.bill.service.account;

import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.yudao.module.bill.controller.admin.account.vo.*;
import cn.iocoder.yudao.module.bill.dal.dataobject.account.AccountDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.bill.dal.mysql.account.AccountMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.bill.enums.ErrorCodeConstants.*;

/**
 * 账户信息 Service 实现类
 *
 * @author mmciel
 */
@Service
@Validated
public class AccountServiceImpl implements AccountService {

    @Resource
    private AccountMapper accountMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createAccount(AccountSaveReqVO createReqVO) {
        // 插入
        AccountDO account = BeanUtils.toBean(createReqVO, AccountDO.class);
        accountMapper.insert(account);
        account.setAccountId((int) (account.getId() + 10000L));
        accountMapper.updateById(account);
        // 返回
        return account.getId();
    }

    @Override
    public void updateAccount(AccountSaveReqVO updateReqVO) {
        // 校验存在
        validateAccountExists(updateReqVO.getId());
        // 更新
        AccountDO updateObj = BeanUtils.toBean(updateReqVO, AccountDO.class);
        accountMapper.updateById(updateObj);
    }

    @Override
    public void deleteAccount(Long id) {
        // 校验存在
        validateAccountExists(id);
        // 删除
        accountMapper.deleteById(id);
    }

    private void validateAccountExists(Long id) {
        if (accountMapper.selectById(id) == null) {
            throw exception(ACCOUNT_NOT_EXISTS);
        }
    }

    @Override
    public AccountDO getAccount(Long id) {
        return accountMapper.selectById(id);
    }

    @Override
    public PageResult<AccountDO> getAccountPage(AccountPageReqVO pageReqVO) {
        return accountMapper.selectPage(pageReqVO);
    }

}